<template>
	<view class="content">
		<view class="top-bar">
			<view class="top-bar-left" @click="backLogin">
				<image class="back-img" src="../../static/common/back1.png"></image>
			</view>
			<view class="top-bar-center">
				<view class="title">{{title}}</view>
			</view>
			<view class="top-bar-right">
				<view class="group-img" @click="history">
					<image src="../../static/img/right-img.png" class="user-img"></image>
				</view>
			</view>
		</view>
		<view class="chat-bag">
			<view class="chat-bottom">
				<view class="chat-head" :style="{marginBottom:'calc(30vh + ' + keyboardHeight+'rpx)'}">
					<image v-if="title === '黄老师' && !isStartWS" src="../../static/bg/huang.png" mode="aspectFit">
					</image>
					<image v-else-if="title === '黄老师' && isStartWS" src="../../static/bg/huang.gif" mode="aspectFit">
					</image>
					<image v-else-if="title === '权老师'" src="../../static/bg/quan.png" mode="aspectFit"></image>
					<image v-else-if="title === '焦老师'" src="../../static/bg/jiao.png" mode="aspectFit"></image>
				</view>
				<view class="chat-content" :style="{bottom:`${keyboardHeight}rpx`}">
					<view class="ai-name">
						黄老师 神经内科教授
					</view>
					<view class="chat-line" />
					<scroll-view class="chat" scroll-y="true" id="scrollview" :scroll-top="scrollTop">
						<view class="chat-main" id="msglistview">
							<view class="chat-ls">
								<view class="chat-problem">
									问题 ： {{chatList.problem}}
								</view>
								<view class="chat-answer">
									回答 ：{{chatList.answer}}
								</view>
								<view class="chat-automatic-voice" @tap="autoplay">
									自动播放
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
		<smartSubmit1 ref="chatSubmit" @inputs="message" @scrollHeight="scrollHeight"></smartSubmit1>
	</view>
</template>

<script>
	// const innerAudioContext = uni.createInnerAudioContext();
	import ttutils from '@/utils/metaverse/ttutils.js'
	import asrauthentication from '@/utils/metaverse/asrauthentication.js';
	import smartSubmit1 from '@/utils/metaverse/SmartSubmit1.vue';
	export default {
		components: {
			smartSubmit1
		},
		data() {
			return {
				socket1: null,
				socket2: null,
				isWebSocket1Open: false,
				isWebSocket2Open: false,
				//滚动距离
				scrollTop: 0,
				chatList: {
					problem: '请描述您的症状 ?',
					answer: '',
					tip: 1
				},
				keyboardHeight: 104,
				isShow: false,
				isStartWS: false,
				smsHistory: [],
				audioChunks: [],
				displayedText: "",
				lineIndex: 0,
				timer: null,
			}
		},
		computed: {

		},
		onUnload() {
			this.stopWebSocket1();
			this.stopWebSocket2();
		},
		beforeDestroy() {

		},
		// 标题栏显示
		onLoad(e) {
			this.title = e.titleName
			uni.setNavigationBarTitle({
				title: e.titleName
			})
			this.$nextTick(function() {
				this.$refs.chatSubmit.setVoice();
			})
		},
		methods: {
			//标题栏右侧图标
			history() {
				this.startWebSocket2();
				// uni.navigateTo({
				// 	url: '../history/history'
				// });
			},
			//标题栏返回按钮
			backLogin() {
				uni.navigateBack()
			},
			loading(title) {
				uni.showToast({
					icon: 'none',
					title: title
				});
			},
			checkJSON(option) {
				try {
					return JSON.parse(option)
				} catch (e) {
					return false
				}
			},
			// 输入框发送的消息
			message(e) {
				if (!this.isWebSocket1Open) {
					this.startWebSocket1(e);
				}
			},
			// 滚动到底部
			getBottom() {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				}, 15)
			},
			scrollHeight(height) {
				this.keyboardHeight = height - 104
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = wx.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			startWebSocket1(e) {
				if (!this.isWebSocket1Open) {
					this.socket1 = uni.connectSocket({
						url: 'ws://172.16.10.124:7861/local_doc_qa/stream-chat/byyl',
						success: data => {
							this.$refs.chatSubmit.setCurrChatStatus(true);
						},
						fail: e => {
							this.loading(JSON.stringify(e));
						}
					});

					this.socket1.onOpen(() => {
						console.log('WebSocket 1 已打开');
						this.isWebSocket1Open = true;
						var data1 = {
							knowledge_base_id: "byyl",
							question: e.message,
							history: this.smsHistory
						}
						this.chatList = {
							problem: e.message,
							answer: ''
						}
						this.displayedText = ''
						var mm = JSON.stringify(data1);
						// 发送消息
						if (this.socket1) {
							uni.sendSocketMessage({
								data: mm,
								success: data => {
									console.log('发送成功', data);
								},
								fail: e => {
									this.loading(JSON.stringify(e));
								}
							})
						}
					});

					this.socket1.onClose(() => {
						this.isWebSocket1Open = false;
					});

					this.socket1.onError((err) => {
						this.isWebSocket1Open = false;
						this.stopWebSocket1();
					});

					this.socket1.onMessage((msg) => {
						if (!this.checkJSON(msg.data)) {
							this.displayedText += msg.data;
						} else {
							var jsonStr = JSON.parse(msg.data);
							if (jsonStr.flag === 'end') {
								this.stopWebSocket1();
								const history1 = [];
								history1.push(this.chatList.problem, this.displayedText)
								if (this.smsHistory.length >= 10) {
									this.smsHistory.splice(0, 1)
								}
								this.smsHistory.push(history1)
								this.startWebSocket2(this.displayedText)
							}
						}
						setTimeout(() => {
							this.getBottom()
						}, 50)
					});
				}
			},
			stopWebSocket1() {
				if (this.isWebSocket1Open) {
					this.socket1.close();
				}
			},
			// 自动播放按钮
			autoplay() {
				// 点击下方的自动播放按钮
				if (this.chatList.answer) {
					this.startWebSocket2(this.chatList.answer);
				} else {
					this.loading('请先描述问题');
				}
			},
			startWebSocket2(strSms) {
				if (!this.isWebSocket2Open) {
					this.socket2 = uni.connectSocket({
						url: "wss://" + ttutils.getUrl(strSms),
						success: data => {
							this.audioChunks = []
						},
						fail: e => {
							this.loading(JSON.stringify(e));
						}
					});

					this.socket2.onOpen(() => {
						this.isWebSocket2Open = true;
					});

					this.socket2.onClose(() => {
						this.isWebSocket2Open = false;
					});

					this.socket2.onError((err) => {
						this.isWebSocket2Open = false;
						this.stopWebSocket2();
					});

					this.socket2.onMessage(({
						data
					}) => {
						if (!this.checkJSON(data)) {
							// 将接收到的二进制数据片段添加到数组中、
							// #ifdef H5
							this.audioChunks.push(data);
							// #endif
							// #ifdef APP-PLUS
							// 将音频数据片段存储到数组中

							// #endif
						} else {
							const data1 = JSON.parse(data)
							if (data1.code == 0 && data1.final == 1) {
								this.stopWebSocket2()
								// #ifdef H5
								// 合并数组中的二进制数据片段
								const concatenatedAudio = new Blob(this.audioChunks);
								// 创建一个新的 Blob URL
								const objectURL = URL.createObjectURL(concatenatedAudio);

								// 创建一个新的音频元素
								const audioElement = new Audio();
								audioElement.src = objectURL;
								// 播放音频
								// audioElement.play();
								audioElement.addEventListener('ended', this.onAudioEnded);
								audioElement.addEventListener("loadedmetadata", () => {
									this.chatList.answer = ""
									const lineDuration = audioElement.duration / this.displayedText.length;
									audioElement.play(); // 开始播放音频
									this.lineIndex = 0; // 重置行索引
									this.timer = setInterval(() => {
										if (this.lineIndex < this.displayedText.length) {
											this.chatList.answer += this.displayedText[this.lineIndex];
											this.lineIndex++;
										} else {
											// 当所有行都显示完毕后，清除定时器
											clearInterval(this.timer);
										}
									}, lineDuration * 1000); // 控制每行文字的显示间隔时间，单位为毫秒
								});

								audioElement.addEventListener("play", () => {
									this.isStartWS = true
								});

								audioElement.addEventListener("error", (error) => {
									this.isStartWS = false
								});
								// #endif
								// #ifdef APP-PLUS

								// #endif
							}
						}
					});
				}
			},
			onAudioEnded(event) {
				// 当语音结束的时候,代表本次聊天结束
				this.$refs.chatSubmit.setCurrChatStatus(false);
				this.isStartWS = false
				const audioElement = event.target;
				audioElement.removeEventListener('ended', this.onAudioEnded);
			},
			stopWebSocket2() {
				if (this.isWebSocket2Open) {
					this.socket2.close();
				}
			},
		}
	}
</script>

<style lang="scss">
	@import "../../commons/css/mucss.scss";

	.content {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: #fff;
		box-sizing: border-box;
		overflow: hidden;
		background-image: url(../../static/bg/bg1.jpg);
		background-size: 100% 100%;
		background-repeat: no-repeat;
		background-attachment: fixed;
		background-position: center;
		margin: 0;
	}

	// 标题栏的样式
	.top-bar {
		background: #176bf1;
		border-bottom: 1px solid $uni-border-color;

		.group-img {
			position: absolute;
			bottom: 10rpx;
			right: 32rpx;
			width: 68rpx;
			height: 68rpx;

			image {
				width: 50rpx;
				height: 50rpx;
				padding: 10rpx;
			}
		}
	}

	.chat-bag {
		.chat-bottom {
			width: 100%;
			position: fixed;
			bottom: 0;

			.chat-head {
				display: flex;
				// margin-bottom:calc(32vh + 104rpx);
				flex-direction: row-reverse;

				image {
					width: 400rpx;
				}

				.rw-head {
					display: inline-block;
					box-sizing: border-box;
					overflow: hidden;
				}
			}

			.chat-content {
				width: 100%;
				height: 30vh;
				position: fixed;
				left: 0;
				background: rgba(0, 0, 0, 0.3);
				color: white;
				overflow: hidden;

				.ai-name {
					text-align: center;
					font-size: 32rpx;
					font-weight: 500;
					padding: 26rpx 0 15rpx 0;
				}

				.chat-line {
					width: 82%;
					height: 1rpx;
					margin-left: 8%;
					background: white;
				}

				.chat {
					height: 100%;

					.chat-main {
						padding-bottom: 80rpx;
						display: flex;
						flex-direction: column;
					}

					.chat-ls {
						display: flex;
						flex-direction: column;
						color: white;

						.chat-problem {
							width: 82%;
							margin-left: 8%;
							margin-top: 25rpx;
							font-size: 28rpx;
						}

						.chat-answer {
							width: 82%;
							margin-left: 8%;
							margin-top: 15rpx;
							font-size: 28rpx;
						}

						.chat-automatic-voice {
							text-align: center;
							font-size: 30rpx;
							margin: 30rpx 0 50rpx 0;
						}
					}
				}
			}
		}
	}
</style>
